const fs = require('fs')
const path = require('path')
/**
 * 读取路径信息
 * @param {string} path 路径
 */
function getStat(path) {
  return new Promise((resolve) => {
    fs.stat(path, (err, stats) => {
      if (err) {
        resolve(false)
      } else {
        resolve(stats)
      }
    })
  })
}

/**
 * 创建路径
 * @param {string} dir 路径
 */
function mkdir(dir) {
  return new Promise((resolve) => {
    fs.mkdir(dir, (err) => {
      if (err) {
        resolve(false)
      } else {
        resolve(true)
      }
    })
  })
}

/**
 * 路径是否存在，不存在则创建
 * @param {string} dir 路径
 */
async function dirExists(dir) {
  let isExists = await getStat(dir)
  //如果该路径且不是文件，返回true
  if (isExists && isExists.isDirectory()) {
    return true
  } else if (isExists) {
    //如果该路径存在但是文件，返回false
    return false
  }
  //如果该路径不存在
  let tempDir = path.parse(dir).dir //拿到上级路径
  //递归判断，如果上级目录也不存在，则会代码会在此处继续循环执行，直到目录存在
  let status = await dirExists(tempDir)
  let mkdirStatus
  if (status) {
    mkdirStatus = await mkdir(dir)
  }
  return mkdirStatus
}

function sepUrl(url) {
  // 解决在win和unix系统下路径分隔符问题
  return url.split(path.sep).join('/')
}

module.exports.getStat = getStat
module.exports.dirExists = dirExists
module.exports.writeFile = async function (filePath, content) {
  filePath = sepUrl(filePath)
  await dirExists(filePath.slice(0, filePath.lastIndexOf('/')))
  return new Promise((resolve) => {
    fs.writeFile(filePath, content, (err) => {
      if (err) return console.log(err)
      console.log(filePath, '写入成功')
      resolve(err)
    })
  })
}

const isPureObject = function (obj) {
  return obj && obj.toString() === '[object Object]'
}

// 查找所有key
const findObjAllKeys = function (obj) {
  let keys = []

  if (Array.isArray(obj)) {
    obj.forEach((v) => {
      keys = keys.concat(findObjAllKeys(v))
    })
  } else if (isPureObject(obj)) {
    for (let p in obj) {
      keys.push(p)
      keys = keys.concat(findObjAllKeys(obj[p]))
    }
  }

  return [...new Set(keys)]
}

module.exports.jsonToStr = function (obj) {
  let keys = findObjAllKeys(obj)
  let str = JSON.stringify(obj, null, 4)
  keys.forEach((v) => {
    if (v.indexOf('-') === -1) {
      str = str.replace(new RegExp(`"${v}":`, 'g'), `${v}:`)
    }
  })

  return str.replace(/"/g, `'`)
}

const getSubPageFileName = function (isFilter) {
  let rootPath = '../src/pages-config'
  let subPath = `${rootPath}/sub-packages`

  let subPackagesFiles = fs
    .readdirSync(path.resolve(__dirname, subPath))
    .filter((v) => v.indexOf('.js') !== -1)

  if (isFilter) {
    return subPackagesFiles.map((v) => v.replace('.js', ''))
  }
  return subPackagesFiles
}
module.exports.getSubPageFileName = getSubPageFileName
module.exports.getPageConfig = function () {
  let rootPath = '../src/pages-config'
  let arr = []
  let pageConfig = require(`${rootPath}/pages.js`)
  let subPackagesFiles = getSubPageFileName()
  subPackagesFiles.forEach((v) => {
    let item = require(`subPath/${v}`)
    let root = item.root
    item.pages.forEach((v2) => {
      arr.push({
        root,
        ...v2,
        path: `${root}/${v2.path}`
      })
    })
  })

  return {
    page: pageConfig,
    all: [...pageConfig, ...arr]
  }
}
